
'''
    Uitls.py
    

    author: ChenJC
    email: isysprey@foxmail.com
    twitter: https://twitter.com/JackChe78220965
'''

import json  # json相关
import os  # 文件流相关
import zipfile  # zip文件
import shutil  # 删除整个文件夹
from jsmin import jsmin  # js压缩
import Log
import win32com.client

# 判断路径是否存在
def hasPath( url ):
    return os.path.exists( url )

# 如果路径不存在 创建路径
def makePath( url ):
    if not hasPath( url ):
        os.makedirs( url )

# 将文本标签转换成字典
def str2Dict(str1, __map=None, assign='='):
    '''
        <script src="src/import-map.json" type="systemjs-importmap" charset="utf-8"> </script>
        
        map{
            src="src/import-map.json",
            type="systemjs-importmap"
            charset="utf-8"
        }
    '''
    try:
        index = str1.find(assign)
        s = 0
        e = 0
        if __map != None:
            __map.clear()
        _map = __map if __map != None else {}
        while(index != -1):
            s = str1.find(' ', s) + 1
            e = str1.find('"', index)+1
            e2 = str1.find('"', e)

            _s = str1[s:index]
            _e = str1[e:e2]
            s = e
            _map[_s] = _e
            index = str1.find(assign, s)  # next
        return _map
    except:
        Log.AppendLineTraceback()


# 从文件中读文本
def fromFile(url):
    try:
        with open( url,'r',encoding='utf-8' ) as fp:
            return fp.read()
    except:
        fp = None
    finally:
        if fp != None:
            fp.close()

# 将文本写入文件
def writeInFile(toFile, content):
    try:
        with open(toFile, 'w', encoding='utf-8') as fp:
            fp.write(content)
    finally:
        fp.close()

# 二进制
def writeBinInFile(url,content):
    try:
        with open(url, 'wb') as fp:
            fp.write(content)
    except:
        fp = None
    finally:
        if not fp:
            fp.close()

# 从本地加载json转换成字典对象
def fromJsonAsDict(url):
    return json.loads((fromFile(url)))

# 将字典对象写入本地
def writeDictInFile(url, dict1):
    writeInFile(url, json.dumps(dict1, ensure_ascii=False, indent=2))

# 弹出本地指定文件夹
def revealInFileExplorer(targetDir):
    try:
        os.startfile(targetDir)
    except:
        os.system("explorer.exe %s" % targetDir)

def encrypt(key,content): # key:密钥,content:明文 lovebread
    EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData')
    EncryptedData.Algorithm.KeyLength = 5
    EncryptedData.Algorithm.Name = 2
    EncryptedData.SetSecret(key)
    EncryptedData.Content = content
    return EncryptedData.Encrypt()

def decrypt(key,content): # key:密钥,content:密文 lovebread
    EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData')
    EncryptedData.Algorithm.KeyLength = 5
    EncryptedData.Algorithm.Name = 2
    EncryptedData.SetSecret(key)
    EncryptedData.Decrypt(content)
    str = EncryptedData.Content
    return str


def JavaScript(content, min=True):
    '''
        讲一段js代码加上<script>标签 并按需压缩
        已弃用 请采用最新的 JavaScriptAndID
    '''
    return '<script>\n'+jsmin(content)+'\n</script>\n' if min else '<script>\n'+content+'\n</script>\n'

def JavaScriptAndID(content,id):
    return f'<script id="{id}">\n{content}\n</script>'

def StyleScript(content, min=True):
    return '<style type="text/css">\n'+jsmin(content) + '\n</style>\n' if min else '<style>\n'+content + '\n</style>\n'



def zipFile(src, dest):
    '''
        src: 目标文件位置   D:/123.txt
        dest: 压缩后输出的zip路径 D:/123.zip
    '''
    with zipfile.ZipFile(dest, 'w',zipfile.ZIP_DEFLATED) as p:
        
        p.write(src,os.path.split(src)[1])

        p.close()     


def zipFiles(src,dest):
    '''
        src: 目标文件夹位置   D:/hellowd
        dest: 压缩后输出的zip路径 D:/hellowd.zip
    '''
    with zipfile.ZipFile(dest, 'w',zipfile.ZIP_DEFLATED) as pZip:
        for folder, _, files in os.walk(src):
            relative_url = folder.replace(src, '')
            for file in files:
                pZip.write(os.path.join(folder,file),os.path.join(relative_url,file))
        pZip.close()

def removeFile(url):
    if os.path.isdir(url):
        shutil.rmtree(url)
    else:
        os.remove(url)